package com.project.homework4_9.util;

import com.project.homework4_9.dao.ILogDao;
import com.project.homework4_9.dao.impl.BaseDao;
import com.project.homework4_9.dao.impl.LogDaoImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.time.LocalTime;

public class UserProxy implements InvocationHandler {
    private Object target;
    private ILogDao logDao = new LogDaoImpl();

    public UserProxy(Object target) {
        this.target = target;
    }

    public Object getProxy() {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                this
        );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        try {
            //执行目标方法
            Object returnObj = method.invoke(target, args);
            return returnObj;
        } catch (Exception e) {
            //xxx类在HH:mm:ss，执行xx方法时，抛出xx异常

            //类名
            String className = target.getClass().getName();
            //得到时分秒
            LocalTime time = LocalTime.now();
            //得到目标方法名
            String methodName = method.getName();
            //得到异常对象的类名
            //e.getCause() 获取异常的真实类型
            String exceptionName = e.getCause().getClass().toString();

            String info = className + "类在" + time + ",执行" + methodName +
                    "方法时，抛出" + exceptionName + "异常";

            System.out.println(info);

            //加入数据库
            logDao.addLog(info);
        }
        return null;
    }
}
